<template>
  <article class="innerPage addAdmin">
    <header class="breadcrumb">
      <x-breadcrumb
        :path="$route.path"
        :title="$route.meta.breadcrumb"
        :startIndex="$route.meta.startIndex"
      >
      </x-breadcrumb>
    </header>
    <section class="userInfo">
      <el-form ref="elForm" :inline="true" :model="formData" :rules="rules">
        <p>
          账号设置
          <span>必填项</span>
        </p>
        <el-form-item label="账号名" prop="account">
          <el-input
            v-model="formData.account"
            placeholder="请输入账号名"
            :disabled="!!$route.query.id"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="tel">
          <el-input
            v-model="formData.tel"
            placeholder="请输入电话号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!$route.query.id">
          <el-input
            type="password"
            clearable
            show-password
            placeholder="请输入新密码"
            autocomplete="off"
            v-model="formData.password"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="confirm_password"
          v-if="!$route.query.id"
        >
          <el-input
            type="password"
            clearable
            show-password
            placeholder="请输入新密码"
            autocomplete="off"
            v-model="formData.confirm_password"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="管理员角色" prop="role_ids">
          <el-select
            v-model="formData.role_ids"
            multiple
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.role_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管辖位置" prop="way" v-if="wayData == 1">
          <el-radio-group v-model="formData.way">
            <el-radio :label="1">全部</el-radio>
            <el-radio :label="2">图书馆</el-radio>
            <el-radio :label="3">书店</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理书店" prop="shop_id" v-if="wayData == 1">
          <el-select
            v-model="formData.shop_id"
            multiple
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in filterList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </section>
    <footer>
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button type="info" @click="pageTurn('/systemSetting/adminList')">
        取消
      </el-button>
    </footer>
  </article>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      formData: {
        account: '',
        username: '',
        password: '',
        confirm_password: '',
        tel: '',
        role_ids: '',
        way: 1,
        shop_id: []
      },
      roleList: [],
      filterList: [],
      rules: {
        account: [
          {
            required: true,
            validator: this.$elValidator?.account,
            trigger: 'blur'
          }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          {
            required: true,
            validator: this.$elValidator?.password,
            trigger: 'blur'
          },
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              var passwordreg =
                /(?![A-Z]*$)(?![a-z]*$)(?![0-9]*$)(?![^a-zA-Z0-9]*$)/
              console.log(passwordreg.test(value))
              if (!passwordreg.test(value)) {
                callback(
                  new Error(
                    '密码必须由大写字母、小写字母、数字中的2种及以上类型组成!'
                  )
                )
              } else {
                callback()
              }
            }
          }
        ],
        confirm_password: [
          {
            required: true,
            validator: this.validatorPassword2,
            trigger: 'blur'
          }
        ],
        tel: [
          {
            required: true,
            validator: this.$elValidator?.phoneNum,
            trigger: 'blur'
          }
        ],
        role_ids: [
          { required: true, message: '请选择管理员角色', trigger: 'blur' }
        ]
      },
      wayData: undefined
    }
  },
  created() {
    //this.setPageTabs()
  },
  activated() {
    if (this.$route.query?.action != 'refresh' || this.$isFirstInPage.get()) {
      let userInfo = localStorage.getItem('token')
      this.wayData = JSON.parse(userInfo).way
      if (this.$route.query.id) {
        this.getdetail()
      }
      this.getRoleList()
      this.getFilterList()
      
    }
   this.setPageTabs()
  },
  computed: {},
  methods: {
    async getdetail() {
      try {
        let res = await this.request({
          url: '/admin/manage/detail',
          method: 'get',
          data: {
            id: this.$route.query.id
          }
        })
        this.formData.id = res.content.id
        this.formData.tel = res.content.tel
        this.formData.account = res.content.account
        this.formData.username = res.content.username
        this.formData.lib_ids = res.content.lib_ids
        let rile = []
        res.content.con_role.map(item => {
          rile.push(item.id)
        })
        this.formData.role_ids = rile
        this.formData.way = res.content.way
        let shop = []
        res.content.con_shop.map(item => {
          shop.push(item.id)
        })
        this.formData.shop_id = shop
        console.log(this.formData)
      } catch (err) {
        this.formData = {}
        this.errorHandler(err)
      }
    },
    async getRoleList() {
      try {
        let res = await this.request({
          url: '/admin/role/filterList',
          method: 'get',
          data: {
            page: 1,
            limit: 10000
          }
        })
        this.roleList = res.content
      } catch (err) {
        this.roleList = []
        this.errorHandler(err)
      }
    },
    async getFilterList() {
      return
      try {
        let res = await this.request({
          url: '/admin/shop/filterList',
          method: 'get',
          data: {
            way: 0
          }
        })
        this.filterList = res.content
      } catch (err) {
        this.filterList = []
        this.errorHandler(err)
      }
    },

    validatorPassword2(rule, v, callback) {
      let reg = /[\w_-]{6,20}/
      if (v) {
        if (reg.test(v)) {
          v + '' === this.formData.password + ''
            ? callback()
            : callback(new Error('两次输入密码不一致!'))
        } else {
          callback(new Error('密码为6到20位数之间'))
        }
      } else {
        callback(new Error('请输入新密码'))
      }
    },
    // 提交数据
    async submit() {
      await this.$refs.elForm.validate()
      let url = undefined
      if (this.$route.query.id) {
        url = '/admin/manage/change'
        this.formData.id = this.$route.query.id
      } else {
        url = '/admin/manage/add'
      }
      await this._submit(url)
    },
    async _submit(url) {
      let shop_id = ''
      if (this.formData.shop_id) {
        shop_id = this.formData.shop_id.join(',')
      }
      try {
        const res = await this.request({
          url,
          method: 'post',
          data: {
            // ...this.formData,
            id: this.formData.id ? this.formData.id : '',
            account: this.formData.account,
            username: this.formData.username,
            password: this.formData.password,
            confirm_password: this.formData.confirm_password,
            tel: this.formData.tel,
            role_ids: this.formData.role_ids.toString(),
            way: this.formData.way || 1,
            shop_id: shop_id
          }
        })
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success'
        })
        setTimeout(() => {
          this.pageTurnParams('adminList', {
            action: 'refresh'
          })
          // this.$router.push({
          //   path: '/systemSetting/adminList'
          // })
        }, 1000)
      } catch (err) {
        this.errorHandler(err)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
